﻿using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.StorageClient;
using SimplePersonManager.Contracts;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimplePersonManager.DataAccess
{
    public class AzureTableStorageRepository : IRepository
    {
        CloudTable _table;
        Microsoft.WindowsAzure.Storage.Table.CloudTableClient _client;
        string _tableName = "Person";

        public AzureTableStorageRepository()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["AzureStorageConnectionString"].ConnectionString;
            var storageAccount = CloudStorageAccount.Parse(connectionString);
            _client = storageAccount.CreateCloudTableClient();
            _table = _client.GetTableReference(_tableName);
            _table.CreateIfNotExists();
        }

        public void StorePerson(Person person)
        {
            var personEntity = PersonEntity.FromPerson(person);

            var insertOperation = TableOperation.Insert(personEntity);
            _table.Execute(insertOperation);
        }

        public Person RetrievePerson(string name)
        {
            var personEntities =
                (from p in _client.GetTableServiceContext().CreateQuery<PersonEntity>(_tableName)
                 where p.RowKey == name
                 select p).AsTableServiceQuery().Execute();
                        
            if (personEntities.Count() == 0)
                return null;

            if (personEntities.Count() > 1)
                throw new ApplicationException(string.Format("Found {0} people named '{1}'", personEntities.Count(), name));

            return personEntities.First().ToPerson();
        }

        public IEnumerable<Person> RetrieveAll()
        {
            var personEntities = _client.GetTableServiceContext().CreateQuery<PersonEntity>(_tableName);

            var result = new List<Person>();
            foreach (var personEntity in personEntities)
                result.Add(personEntity.ToPerson());

            return result;
        }
    }
}
